package com.houduan.controller;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.annotation.*;
import java.nio.file.*;

@MultipartConfig
public class StudentInfoServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单提交的参数
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String age = request.getParameter("age");
        String major = request.getParameter("major");
        String phone = request.getParameter("phone");
        String idCard = request.getParameter("idCard");
        String college = request.getParameter("college");
        String className = request.getParameter("class");

        // 处理文件上传（头像）
        Part avatarPart = request.getPart("avatar");
        String avatarFileName = null;
        if (avatarPart != null && avatarPart.getSize() > 0) {
            avatarFileName = Paths.get(avatarPart.getSubmittedFileName()).getFileName().toString();
            String uploadPath = getServletContext().getRealPath("/uploads");
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) uploadDir.mkdirs();
            avatarPart.write(uploadPath + File.separator + avatarFileName);
        }

        // 将数据存储到请求中，以便在 JSP 页面中访问
        request.setAttribute("name", name);
        request.setAttribute("gender", gender);
        request.setAttribute("age", age);
        request.setAttribute("major", major);
        request.setAttribute("phone", phone);
        request.setAttribute("idCard", idCard);
        request.setAttribute("avatarFileName", avatarFileName);
        request.setAttribute("college", college);
        request.setAttribute("className", className);

        // 转发请求到 student_info.jsp 页面
        RequestDispatcher dispatcher = request.getRequestDispatcher("student_info.jsp");
        dispatcher.forward(request, response);
    }
}
